//
//  WidgetTemplate.m
//  WebClipper
//
//  Created by Daniel Braun on 25/04/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "WidgetTemplate.h"
#import "WidgetVariable.h"
#import "StringExtension.h"
#import "MyDocument.h"

@implementation WidgetTemplate

- (void) dealloc {
	[path release];
	[name release];
	[fullname release];
	[_variableList release];
	[super dealloc];
}

- initWithPath:(NSString *)p
{
	self=[super init];
	if (!self) return nil;
	path=[p retain];
	NSArray *a=[path pathComponents];
	fullname=[[a lastObject]retain];
	name=[[[fullname componentsSeparatedByString:@"."]objectAtIndex:0]retain];
	if ([fullname hasSuffix:@".wdgtproj"]) {
		isWdgtProj=YES;
	}
	return self;
}

- (NSString *) wpath
{
	if (!isWdgtProj) return path;
	return [path stringByAppendingPathComponent:@"project.wdgt"];
}
- (NSString *) name
{
	return name;
}
	
- (NSString *) iconPath
{
	return [NSString stringWithFormat:@"file://%@/Icon.png", [self wpath]];
}

- (NSArray *) _getVarFromJs:(NSString *)file
{
	NSError *err;
	NSString *s=[NSString stringWithContentsOfFile:file
					      encoding:NSISOLatin1StringEncoding
						 error:&err];
	if (!s) return nil;
	NSMutableArray *res=[NSMutableArray arrayWithCapacity:10];
	NSArray *sp=[s componentsSeparatedByString:@"webExtract.extractForKey_("];
	NSLog(@"split %d\n", [sp count]);
	unsigned int i, count = [sp count];
	for (i = 0; i < count; i++) {
		NSString *s=[sp objectAtIndex:i];
		if (![s hasPrefix:@"\""]) continue;
		//if (!(i%2)) continue;
		s = [s stringBetween:@"\"" and:@"\")" inclusive:NO];
		NSLog(@"got item %@\n", s);
		WidgetVariable *wv=[[[WidgetVariable alloc]init]autorelease];
		[wv setName:s];
		//[wv setOk:NO];
		[res addObject:wv];
	}
	return res;
}
- (NSArray *) variableList
{
	if (!_variableList) {
		_variableList=[[NSMutableArray arrayWithCapacity:20]retain];
		NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] 
		enumeratorAtPath:path];
		NSString *fname=nil;
		while ((fname=[direnum nextObject])) {
			//[direnum skipDescendents];
			if (![fname hasSuffix:@".js"]) continue;
			//NSLog(@"got file %@/%@", path, fname);
			NSArray *v=[self _getVarFromJs:[NSString stringWithFormat:@"%@/%@", path, fname]];
			if (v) [_variableList addObjectsFromArray:v];
		}
	}
	return _variableList;
}

- (BOOL) variablesOk
{
	NSArray *a=[self variableList];
	unsigned int i, count = [a count];
	for (i = 0; i < count; i++) {
		WidgetVariable * wa = [a objectAtIndex:i];
		if (![wa ok]) return NO;
	}
	if (!count) return NO;
	return YES;
}




- (BOOL) buildWidgetIn:(NSString *)destPath
{
	//BOOL ok=[m createDirectoryAtPath:tp
	//		      attributes:nil];
	//NSLog(@"creat dir : %@\n", ok ? @"ok" :@"nok");
	//if (!ok) return;
	NSFileManager *m=[NSFileManager defaultManager];
	if ([m fileExistsAtPath:destPath]) {
		BOOL result = NSRunAlertPanel(@"WebExtractor", 
					 @"File %@ already exist.", @"Overwrite", @"Stop",  NULL,
				destPath,
				 nil);
	
		if (result != NSAlertDefaultReturn) return NO;
		[m removeFileAtPath:destPath handler:self];
	}
	BOOL ok=[m copyPath:path toPath:destPath handler:self];
	if (!ok) return ok;
	NSString *plugin=[[NSBundle mainBundle]pathForResource:@"WebExtractorDash.widgetplugin" ofType:nil];
	NSString *dwpath=isWdgtProj ? 
		[destPath stringByAppendingPathComponent:@"project.wdgt"] :
		destPath;
	ok=[m copyPath:plugin toPath:[dwpath stringByAppendingPathComponent:@"WebExtractorDash.widgetplugin"] handler:self];
	MyDocument *md=[[NSDocumentController sharedDocumentController]currentDocument];
	if (!md) return NO;
	NSError *err;
	NSURL *spath=[NSURL fileURLWithPath:[dwpath stringByAppendingPathComponent:@"main.webExtract"]];
	ok=[md writeToURL:spath ofType:@"webExtract" error:&err];
	if (!ok) {
		NSLog(@"error saving : %@\n", err);
	}
	return ok;
}


- (void) testWidget
{
	//NSString *tmp=NSTemporaryDirectory();
	//NSString *tmp=NSDesktopDirectory
	NSArray *a=NSSearchPathForDirectoriesInDomains(NSDesktopDirectory,NSUserDomainMask,YES);
	NSString *tmp=[a objectAtIndex:0];
	NSString *dp=[[tmp stringByAppendingPathComponent:@"webextractortest"]
		stringByAppendingPathComponent:fullname];
	BOOL ok=[self buildWidgetIn:dp];
	NSLog(@"creat widget : %@\n", ok ? @"ok" :@"nok");
	NSWorkspace *wp=[NSWorkspace sharedWorkspace];
	[wp openFile:dp withApplication:@"Dashcode"];
	
}

- (void)fileManager:(NSFileManager *)manager willProcessPath:(NSString *)path
{
}
-(BOOL)fileManager:(NSFileManager *)manager
        shouldProceedAfterError:(NSDictionary *)errorInfo
{
	int result;
	result = NSRunAlertPanel(@"WebExtractor", @"File  operation error:  %@ with file: %@", @"Proceed", @"Stop",  NULL,
				 [errorInfo objectForKey:@"Error"],
				 [errorInfo objectForKey:@"Path"]);
	
	if (result == NSAlertDefaultReturn) return YES;
	else return NO;
}



@end
